/**
 * 
 */
package br.gov.sjc.socialalimenta;

import java.util.Calendar;

import br.org.sjc.validacao.ManipulaData;
import br.org.sjc.validacao.Sair;
import br.org.sjc.validacao.ValidaCPFCNPJ;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * @author rodrigo.ramos
 *
 */
public class DocumentosActivity extends Sair {
	//Declara base de dados
	public static SQLiteDatabase BancoDados = null;
	public static String nomeBanco = "SocialAlimenta";
	public static String TAG = "DocumentosActivity";
	public void openDB(){
		try{
			BancoDados = openOrCreateDatabase(nomeBanco,MODE_WORLD_READABLE,null);
			Log.v("DocumentosActivity", "BancoDados.openOrCreateDatabase();");
		}catch (Exception E){
			Log.e("DocumentosActivity", "Erro em BancoDados.close();"+E.getMessage());
		} 
	}
	public void closeDB(){
		BancoDados.close();
		Log.v("DocumentosActivity", "BancoDados.close();");
	}

	/*
	 * Retirado e inserido caixa de texto
	static final int DATE_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID3 = 3;
	static final int DATE_DIALOG_ID2 = 2;
	 */

	//Declara TextBox
	EditText tbRgNumero, tbRGOrgao, tbCPF,tbCPFExp ;
	EditText tbCTPSn, tbCTPSSerie,tbCTPSExp,tbNisNum ;
	EditText tbCPFDataExp,tbRGDataExp,tbCTPSDataExp;

	//Declara Spinner
	Spinner spRGUF, spCTPSUF;
	
	// Declara Buttons
	Button btnDVoltar, btnDIr, btnCPFExp, btnRGDataExp, btnCTPSDataExp;

	//Declara base de dados
	//SQLiteDatabase BancoDados = SocialAlimenta2Activity.BancoDados ;

	//Declara Variáveis
	String data, databtnCPFExp, databtnRGDataExp, databtnCTPSDataExp;

	//Pega o numero do Sias em uso atual
	NumeroSias ns = new NumeroSias();
	int NumSias = ns.getNumeroDaFamilia();
	int idMembroSias = ns.getNumeroDoMembroDaFamilia();
	int ID;

	//Declara Cursor
	Cursor cVerifica;

	/* @Override
    protected Dialog onCreateDialog(int id) {
        Calendar calendario = Calendar.getInstance();

        int ano = calendario.get(Calendar.YEAR);
        int mes = calendario.get(Calendar.MONTH);
        int dia = calendario.get(Calendar.DAY_OF_MONTH);

        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, ano, mes, dia);
        case DATE_DIALOG_ID3:
            return new DatePickerDialog(this, mDateSetListener, ano, mes, dia);
        case DATE_DIALOG_ID2:
            return new DatePickerDialog(this, mDateSetListener, ano, mes, dia);
        }
        return null;
    }
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            data = String.valueOf(dayOfMonth) + " /"
                    + String.valueOf(monthOfYear+1) + " /" + String.valueOf(year);
            Toast.makeText(DocumentosActivity.this,
                    "DATA = " + data, Toast.LENGTH_SHORT)
                    .show();
            onResume();


            }
    };*/
	/*
	 * 
    @Override
    public void onClick(View v) {
    	switch (v.getId()) {
        case R.docs.btnCPFDataExp:
        	//if (v == btnCPFExp){
        	showDialog(DATE_DIALOG_ID);
        	databtnCPFExp = data;
        	btnCPFExp.setText(databtnCPFExp);

        	 break;
        case R.docs.btnRGDataExp:
        	showDialog(DATE_DIALOG_ID);
        	databtnRGDataExp = data;
        	btnRGDataExp.setText(databtnRGDataExp);

        	break;
        case R.docs.btnCTPSDataExp:
        	showDialog(DATE_DIALOG_ID);
        	databtnCTPSDataExp = data;
        	btnCTPSDataExp.setText(databtnCTPSDataExp);

        	break;
        case R.docs.btnVoltar:
            // InitComponents 
            Intent ittDVoltar = new Intent(getApplicationContext(), EscolaridadeActivity.class);
            startActivity(ittDVoltar);
            break;
        case R.docs.btnIr:
        	salvaDados(NumSias,idMembroSias, tbRgNumero.getText().toString(), tbRGOrgao.getText().toString(), tbRGUF.getText().toString(), 
        			databtnRGDataExp, tbCPF.getText().toString(),databtnCPFExp,
        			tbCTPSn.getText().toString(),tbCTPSSerie.getText().toString(), databtnCTPSDataExp, 
        			tbNisNum.getText().toString());
            Intent ittDIr = new Intent(getApplicationContext(), TrabalhoActivity.class);
            startActivity(ittDIr);
            break;
           }
        }*/

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.documentos);
		registerBaseActivityReceiver();
		openDB();

		// capture our View elements
		tbRgNumero = (EditText) findViewById(R.docs.tbRgNumero);
		tbRGOrgao = (EditText) findViewById(R.docs.tbRGOrgao);
		spRGUF = (Spinner) findViewById(R.docs.spRGUF);
		spCTPSUF = (Spinner) findViewById(R.docs.spCTPSUF);
		tbCPF = (EditText) findViewById(R.docs.tbCPF);
		tbCTPSn = (EditText) findViewById(R.docs.tbCTPSn);
		tbCTPSSerie = (EditText) findViewById(R.docs.tbCTPSSerie);
		tbNisNum = (EditText) findViewById(R.docs.tbNisNum);
		tbCPFDataExp = (EditText) findViewById(R.docs.tbCPFDataExp);
		tbRGDataExp = (EditText) findViewById(R.docs.tbRGDataExp);
		tbCTPSDataExp = (EditText) findViewById(R.docs.tbCTPSDataExp);
		// Declara TextViews e LV
		ArrayAdapter<CharSequence> adpRGUF;
		ArrayAdapter<CharSequence> adpCTPSUF;

		// capture our View elements
		//btnCPFExp = (Button) findViewById(R.docs.btnCPFDataExp);
		//btnRGDataExp = (Button) findViewById(R.docs.btnRGDataExp);
		//btnCTPSDataExp = (Button) findViewById(R.docs.btnCTPSDataExp);
		btnDIr = (Button) findViewById(R.docs.btnIr);
		btnDVoltar = (Button) findViewById(R.docs.btnVoltar);
		//RG
		adpRGUF = ArrayAdapter.createFromResource(
				this, R.array.UF,
				android.R.layout.simple_spinner_item);
		adpRGUF.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spRGUF.setAdapter(adpRGUF);
		//CTPS
		adpCTPSUF = ArrayAdapter.createFromResource(
				this, R.array.UF,
				android.R.layout.simple_spinner_item);
		adpCTPSUF.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spCTPSUF.setAdapter(adpCTPSUF);

		/** Inicia o set de dados caso haja dados */
		if (verificaRegistro()){
			setarDados(ID);
			Log.v(TAG, "onCreate() Com dados do SiasN: "+NumSias+"ID: "+ID);
		}else{
			//Num tem seNão
			Log.v(TAG, "onCreate() Com dados vazios ");
		}


		/** Acao do botao Voltar */
		btnDVoltar.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				// InitComponents 
				Intent ittDVoltar = new Intent(getApplicationContext(), EscolaridadeActivity.class);
				closeDB();
				startActivity(ittDVoltar);
			}
		});//fim acao do botao voltar

		/** Acao do botao Prox */
		btnDIr.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				
				int erro = 0;
				// Existe algo em CPF
				if(tbCPF.getText().toString().equals("")){
					Log.i(TAG, "btnDIr.setOnClickListener - tbCPF vazio");
				}else{
					ValidaCPFCNPJ valida = new ValidaCPFCNPJ();
					if (valida.validarId(tbCPF.getText().toString(),"CPF")){
						Log.i(TAG, "btnDIr.setOnClickListener - cpf válido:"+tbCPF.getText().toString());
					}else{
						Toast.makeText(DocumentosActivity.this, "CPF Inválido", Toast.LENGTH_LONG).show();
						Log.w(TAG, "btnDIr.setOnClickListener - CPF Inválido:"+tbCPF.getText().toString());
						erro++;
					}
				}
				// Existe algo em CPF tbCPFDataExp
				if (tbCPFDataExp.getText().toString().equals("")){
					Log.i(TAG, "btnDIr.setOnClickListener - tbCPFDataExp vazio");
				}else{ 
					ManipulaData data = new ManipulaData();
					try {
						if (!data.DataOk(tbCPFDataExp.getText().toString()) || data.DataMaiorQueHoje(tbCPFDataExp.getText().toString())||!data.MaiorQue1900(tbCPFDataExp.getText().toString())){
							Toast.makeText(DocumentosActivity.this, "Data de expedição de CPF Inválida", Toast.LENGTH_LONG).show();
							Log.w(TAG, "btnDIr.setOnClickListener - CPF Data maior que hoje ou Inválida:"+tbCPFDataExp.getText().toString());
							erro++;
						}

					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(DocumentosActivity.this, "Verifique os campos de Expedição", Toast.LENGTH_LONG).show();
						Log.w(TAG, "btnDIr.setOnClickListener - Data Inválida: "+e.getMessage()+" /"+tbCPFDataExp.getText().toString());
						erro++;
					}
				}
				// Existe algo em RG tbRGDataExp
				if (tbRGDataExp.getText().toString().equals("")){
					Log.i(TAG, "btnDIr.setOnClickListener - tbRGDataExp vazio");
				}else{
					ManipulaData data3 = new ManipulaData();
					try {
						if (!data3.DataOk(tbRGDataExp.getText().toString()) || data3.DataMaiorQueHoje(tbRGDataExp.getText().toString())||!data3.MaiorQue1900(tbRGDataExp.getText().toString())){
							Toast.makeText(DocumentosActivity.this, "Data de expedição de RG Inválida", Toast.LENGTH_LONG).show();
							Log.w(TAG, "btnDIr.setOnClickListener - RG Data maior que hoje ou Inválida:"+tbRGDataExp.getText().toString());
							erro++;
						}
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(DocumentosActivity.this, "Verifique os campos de data", Toast.LENGTH_LONG).show();
						Log.w(TAG, "btnDIr.setOnClickListener - Data Inválida: "+e.getMessage()+" /"+tbRGDataExp.getText().toString());
						erro++;
					}
				}
				// Existe algo em CTPS tbCTPSDataExp
				if (tbCTPSDataExp.getText().toString().equals("")){
					Log.i(TAG, "btnDIr.setOnClickListener - tbCTPSDataExp vazio");
				}else{
					ManipulaData data2 = new ManipulaData();
					try {
						if (!data2.DataOk(tbCTPSDataExp.getText().toString()) ||data2.DataMaiorQueHoje(tbCTPSDataExp.getText().toString())||!data2.MaiorQue1900(tbCTPSDataExp.getText().toString())){
							Toast.makeText(DocumentosActivity.this, "Data de expedição de CTPS Inválida", Toast.LENGTH_LONG).show();
							Log.w(TAG, "btnDIr.setOnClickListener - CTPS Data maior que hoje ou Inválida:"+tbCTPSDataExp.getText().toString());
							erro++;
						}
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(DocumentosActivity.this, "Verifique os campos Expedição", Toast.LENGTH_LONG).show();
						Log.w(TAG, "btnDIr.setOnClickListener - ERRO - Data Inválida: "+e.getMessage()+" /"+tbCTPSDataExp.getText().toString());
						erro++;
					}
				}
				//SE Não HOUVER ERRO
				if (erro == 0){
					if (verificaRegistro()){
						alteraRegistro(ID);
					}else{
						salvaDados(NumSias,idMembroSias, tbRgNumero.getText().toString(), tbRGOrgao.getText().toString(), spRGUF.getSelectedItem().toString(), 
								tbRGDataExp.getText().toString(), tbCPF.getText().toString(),tbCPFDataExp.getText().toString(),
								tbCTPSn.getText().toString(),tbCTPSSerie.getText().toString(), tbCTPSDataExp.getText().toString(), 
								spCTPSUF.getSelectedItem().toString(), tbNisNum.getText().toString());
					}
					/** InitComponents */
					Intent ittDIr = new Intent(getApplicationContext(), Trabalhomain.class);
					closeDB();
					startActivity(ittDIr);
				}else{
					
					Log.e(TAG, "btnDIr.setOnClickListener - erro != 0");
				}
			}
		});
		//fim acao do botao Px

		/* add a click listener to the button
       btnRGDataExp.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            	databtnRGDataExp = data;
            	data="0";
            	btnRGDataExp.setText(databtnRGDataExp);
            }
        });  */
		/* // add a click listener to the button
       btnCTPSDataExp.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID3);
                databtnCTPSDataExp = data;
                data="0";
                btnCTPSDataExp.setText(databtnCTPSDataExp);
            }
        }); */
		/*  btnCPFExp.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               showDialog(DATE_DIALOG_ID2);
           	databtnCPFExp = data;
           	data="0";
           	btnCPFExp.setText(databtnCPFExp);
           }
       });   */
	}
	//CREATE TABLE IF NOT EXISTS tab_SocialA_Documentos(_id INTEGER PRIMARY KEY, SiasN INT, RG TEXT,RGExp TEXT, RGUF TEXT, RGDataExp TEXT, CPF TEXT, CPFDataExp TEXT, CTPS TEXT, CTPSSerie TEXT, CTPSDataExp TEXT, NIS TEXT

	public void salvaDados(int string, int string2, String string3, String string4, String string5, String string6, 
			String string7, String string8, String string9, String string10, String string11, String string12, String string13){
		try{

			String SQL = "INSERT INTO tab_SocialA_Documentos(SiasN,idMembro, RG ,RGExp, RGUF , RGDataExp , CPF, " +
					"CPFDataExp , CTPS , CTPSSerie , CTPSDataExp,CTPSUF, NIS ) VALUES ("+string+", '"+string2+"'," +
					"'"+string3+"', '"+string4+"','"+string5+"', '"+string6+"','"+string7+"','"+string8+"'," +
					"'"+string9+"','"+string10+"','"+string11+"','"+string12+"','"+string13+"')";
			BancoDados.execSQL(SQL);
			Toast.makeText(this, "Gravando Dados da Família:"+NumSias+"/"+idMembroSias, Toast.LENGTH_LONG).show();
		}catch(Exception erro) {
			mensagemAlerta("Erro","Ocorreu um erro ao gravar");
			Log.e(TAG, "salvaDados() "+erro.getMessage()+"/"+erro.getCause());
		}
	}
	public void mensagemAlerta(String AlertTitle, String MSGAlert){
		AlertDialog.Builder Mensagem = new AlertDialog.Builder(DocumentosActivity.this);
		Mensagem.setTitle(AlertTitle);
		Mensagem.setMessage(MSGAlert);
		Mensagem.setNeutralButton("Ok", null);
		Mensagem.show();
	}
	/*public void addValoresDate(){
		databtnCPFExp = data;
		//btnRGDataExp.setText(databtnRGDataExp);
		databtnRGDataExp = data;
		// btnCTPSDataExp.setText(databtnCTPSDataExp);
		databtnCTPSDataExp = data;
		// btnCPFExp.setText(databtnCPFExp);
	}*/
	//SiasN,idMembro, RG ,RGExp, RGUF , RGDataExp , CPF, CPFDataExp , CTPS , CTPSSerie , CTPSDataExp, NIS
	public boolean verificaRegistro(){
		boolean Retorno = false;
		try{
			String SQLQuery = "Select * from tab_SocialA_Documentos WHERE SiasN="+NumSias+" AND idMembro="+idMembroSias;
			cVerifica = BancoDados.rawQuery(SQLQuery, null);
			if (cVerifica.getCount() !=0 ){
				cVerifica.moveToFirst();
				ID = cVerifica.getInt(cVerifica.getColumnIndex("_id"));
				Retorno = true;
				Log.i(TAG, "verificaRegistro() TRUE ");
			}
		}catch (Exception Err){
			mensagemAlerta("Erro","Erro Encontrado");
			Log.e(TAG, "verificaRegistro() "+Err.getMessage());
		}
		return Retorno;

	}
	public void setarDados(int Posicao){
		try {
			String SQL2 = "SELECT * FROM tab_SocialA_Documentos WHERE _id="+Posicao+" ";
			Log.v("DocumentosActivity", "setarDados() Posição: "+Posicao);
			Cursor c = BancoDados.rawQuery(SQL2, null);
			c.moveToFirst();

			do {
				tbRgNumero.setText(c.getString(c.getColumnIndex("RG")));
				tbRGOrgao.setText(c.getString(c.getColumnIndex("RGExp")));
				//spRGUF.setText(c.getString(c.getColumnIndex("RGUF")));
				tbRGDataExp.setText(c.getString(c.getColumnIndex("RGDataExp")));
				tbCPF.setText(c.getString(c.getColumnIndex("CPF")));
				tbCPFDataExp.setText(c.getString(c.getColumnIndex("CPFDataExp")));
				tbCTPSn.setText(c.getString(c.getColumnIndex("CTPS")));
				tbCTPSSerie.setText(c.getString(c.getColumnIndex("CTPSSerie")));
				tbCTPSDataExp.setText(c.getString(c.getColumnIndex("CTPSDataExp")));
				tbNisNum.setText(c.getString(c.getColumnIndex("NIS")));
				
				//RG
    			ArrayAdapter<CharSequence> adpURGUF = ArrayAdapter.createFromResource(
    			        this, R.array.UF,
    			        android.R.layout.simple_spinner_item);
    			adpURGUF.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    			int iURGUF = adpURGUF.getPosition(c.getString(c.getColumnIndex("RGUF")));
    			spRGUF.setSelection(iURGUF);
    			//CTPS
    			ArrayAdapter<CharSequence> adpUCTPSUF = ArrayAdapter.createFromResource(
    			        this, R.array.UF,
    			        android.R.layout.simple_spinner_item);
    			adpUCTPSUF.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    			int iUCTPSUF = adpUCTPSUF.getPosition(c.getString(c.getColumnIndex("CTPSUF")));
    			spCTPSUF.setSelection(iUCTPSUF);
    			
			}while(c.moveToNext());
			Log.v("DocumentosActivity", "setarDados() TRUE ");
		}catch (Exception E){
			mensagemAlerta("Erro","Ocorreu um erro inesperado");
			Log.e("DocumentosActivity", "Erro em setarDados() "+E.getMessage());
		}
	}
	public void alteraRegistro(int id){
		try{
			String uSQL = "UPDATE tab_SocialA_Documentos SET " +
					" RG='"+tbRgNumero.getText().toString()+"'," +
					" RGExp='"+tbRGOrgao.getText().toString()+"'," +
					" RGUF='"+spRGUF.getSelectedItem().toString()+"'," +
					" RGDataExp='"+tbRGDataExp.getText().toString()+"'," +
					" CPF='"+tbCPF.getText().toString()+"'," +
					" CPFDataExp='"+tbCPFDataExp.getText().toString()+"'," +
					" CTPS='"+tbCTPSn.getText().toString()+"'," +
					" CTPSSerie='"+tbCTPSSerie.getText().toString()+"'," +
					" CTPSDataExp='"+tbCTPSDataExp.getText().toString()+"'," +
					" CTPSUF='"+spCTPSUF.getSelectedItem().toString()+"'," +
					" NIS='"+tbNisNum.getText().toString()+"'" +
					" WHERE _id="+id+" ";
			BancoDados.execSQL(uSQL);
			Toast.makeText(DocumentosActivity.this, "Alterado", Toast.LENGTH_LONG).show();
			Log.v("DocumentosActivity", "alteraRegistro() realizado com sucesso ");
		}catch(Exception Err){
			mensagemAlerta("Erro","Ocorreu um erro inesperado");
			Log.e("DocumentosActivity", "alteraRegistro() erro: "+Err.getMessage());

		}

	}

	@Override
	protected void onResume() {
		//quando a Activity main receber o foco novamente abre-se novamente a conexão
		openDB();
		//método responsável pela atualiza da lista de dados na tela
		//adapter.notifyDataSetChanged();
		super.onResume();
	}
	@Override
	protected void onPause() {

		//toda vez que o programa peder o foco fecha-se a conexão com o BD
		closeDB();
		super.onPause();
	}
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	unRegisterBaseActivityReceiver();
    	finish();
    }

}
